package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.enums.BrandStatusEnum;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.BankerCheckStatusRequest;
import com.ytjj.qmyx.supplychain.common.model.request.BankerSiteRequest;
import com.ytjj.qmyx.supplychain.common.model.request.BankerUpdatePutOnRequest;
import com.ytjj.qmyx.supplychain.common.model.request.BankerUpdateReleaseRequest;
import com.ytjj.qmyx.supplychain.common.model.response.BankerResponse;
import com.ytjj.qmyx.supplychain.common.model.response.BankerSiteResponse;
import com.ytjj.qmyx.supplychain.mapper.BankerInfoMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerMessageMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerSiteMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBanker;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerInfo;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerMessage;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerSite;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class BankerSiteService extends AbstractService<BankerSiteMapper, YxBankerSite> {
    @Autowired
    private BankerService bankerService;
    @Autowired
    private BankerBrandService bankerBrandService;
    @Autowired
    private BankerProductService bankerProductService;
    @Resource
    private BankerSiteMapper bankerSiteMapper;
    @Resource
    private BankerInfoMapper bankerInfoMapper;
    @Resource
    private BankerMessageMapper bankerMessageMapper;
    @Value(value = "${history-off:true}")
    private boolean historyOff;

    public YxBankerSite queryByBankerId(Integer bankerId) {
        Example example = new Example(YxBankerSite.class);
        example.createCriteria().andEqualTo("bankerId", bankerId);
        example.orderBy("id").desc();
        YxBankerSite bankerSite = bankerSiteMapper.selectOneByExample(example);
        return bankerSite;
    }

    public Integer syncSite(YxBankerSite bankerSite) {
        YxBanker info = bankerService.getUserInfo();
        // 根据bankerId获取供应商网站 如果存在-修改 不存在-增加
        YxBankerSite site = queryByBankerId(info.getId());
        Integer count = 0;

        if(null == site) {
            bankerSite.setStatus(0);
            bankerSite.setBankerId(info.getId());
            bankerSite.setBankerName(info.getName());
            bankerSite.setCreateTime(new Date());
            bankerSite.setCheckStatus(BrandStatusEnum.WAIT_CHECK.getCode());
            count = insertSelective(bankerSite);
        } else {
            bankerSite.setStatus(0);
            bankerSite.setBankerId(info.getId());
            bankerSite.setUpdateTime(new Date());
            bankerSite.setCheckStatus(BrandStatusEnum.WAIT_CHECK.getCode());
            bankerSite.setCheckMsg(null);
            count = updateByPrimaryKeySelective(bankerSite);
        }
        try {
            log.info("===doUpdateBrandBankerSiteIdIsNullData：{},{}===", info.getId(), bankerSite.getId());
            //更新供应商下面品牌未绑定店铺的数据
            doUpdateBrandBankerSiteIdIsNullData(info.getId(), bankerSite.getId());
        } catch (Exception e) {
            log.error("===doUpdateBrandBankerSiteIdIsNullData is err:", e);
        }
        return count;
    }

    private void doUpdateBrandBankerSiteIdIsNullData(Integer bankerId, Integer bankerSiteId) {
        bankerBrandService.doUpdateBrandBankerSiteIdIsNullData(bankerId, bankerSiteId);
    }

    public CommonResult checkStatus(BankerCheckStatusRequest request) {
        log.info("供应商店铺审核参数：{}", request);
        YxBankerSite bankerSite = selectByPrimaryKey(request.getId());
        if (null == bankerSite) {
            return CommonResult.failed("找不到供应商店铺信息");
        }
        Example example = new Example(YxBankerInfo.class);
        example.createCriteria().andEqualTo("bankerId", bankerSite.getBankerId());
        YxBankerInfo bankerInfo = bankerInfoMapper.selectOneByExample(example);
        if (null == bankerInfo) {
            return CommonResult.failed("找不到供应商对应的主体信息");
        }
        if (bankerInfo.getStatus() == 1) {
            return CommonResult.failed("供应商对应的主体信息未审核");
        }
        if (!bankerSite.getCheckStatus().equals(BrandStatusEnum.WAIT_CHECK.getCode())) {
            return CommonResult.failed("该店铺信息已审核，不能重复审核");
        }
        bankerSite.setCheckStatus(request.getStatus());
        bankerSite.setCheckMsg(request.getMsg());
        if (BrandStatusEnum.PASS.getCode().equals(request.getStatus())) {
            bankerSite.setReleased(0);
            bankerSite.setStatus(1);
        } else {
            bankerSite.setStatus(0);
        }
        int count = updateByPrimaryKeySelective(bankerSite);
        if (count <= 0) {
            return CommonResult.failed("审核失败");
        }
        try{
            YxBankerMessage message = new YxBankerMessage();
            message.setBankerId(bankerInfo.getBankerId());
            message.setBankerName(bankerInfo.getBankerName());
            message.setRemarks("您的店铺信息：" + bankerSite.getTitle() + (request.getStatus() == 1 ? " 已通过审核！" : "未通过审核,原因:" + request.getMsg()));
            message.setStatus(0);
            message.setType(request.getStatus() == 1 ? 5 : 6);
            message.setCreateTime(new Date());
            bankerMessageMapper.insertSelective(message);
        } catch (Exception e) {
            log.error("===记录bankerMessage异常，{}", e);
        }

        return CommonResult.success("审核成功");
    }

    public CommonResult release(BankerUpdateReleaseRequest request) {
        YxBankerSite site = selectByPrimaryKey(request.getId());
        if (null == site) {
            return CommonResult.failed("找不到店铺信息");
        }
        site.setReleased(request.getStatus());
        int count = updateByPrimaryKey(site);
        if (count > 0) {
            return CommonResult.success("释放成功");
        }
        return CommonResult.failed("释放失败");
    }

    public YxBankerSite selectByBankerId(Integer bankerId) {
        Example example = new Example(YxBankerSite.class);
        example.createCriteria().andEqualTo("bankerId", bankerId);
        YxBankerSite bankerSite = selectOneByExample(example);
        return bankerSite;
    }

    @Transactional
    public CommonResult updateBankerSitePutOn(BankerUpdatePutOnRequest request) {
        log.info("===供应商店铺下架参数：{}===", request);
        YxBankerSite bankerSite = selectByBankerId(request.getBankerId());
        if (null == bankerSite) {
            return CommonResult.failed("找不到待下架的店铺信息");
        }
        bankerSite.setStatus(request.getStatus());
        int count = updateByPrimaryKeySelective(bankerSite);
        if (count <= 0) {
            return CommonResult.failed("供应商店铺下架失败");
        }
        //下架供应商店铺下的品牌信息
        bankerBrandService.brandPutOnBySiteId(bankerSite.getId(), request.getStatus());
        //下架供应商的商品信息
        bankerProductService.updateStatusByBankerId(request.getBankerId(), 2);
        return CommonResult.success("下架成功");
    }

    public YxBankerSite getSite() {
        YxBanker banker = bankerService.getUserInfo();
        Integer bankerId = banker.getId();
        Example example = new Example(YxBankerSite.class);
        example.createCriteria().andEqualTo("bankerId", bankerId);
        YxBankerSite bankerSite = bankerSiteMapper.selectOneByExample(example);
        if (null == bankerSite) {
            boolean isOldInfo = false;// true-历史数据  false-新数据
            try {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                Date upLineTimeDate = sdf.parse("2021-04-13 00:00:00");
                if (banker.getCreateTime().before(upLineTimeDate) && historyOff) {
                    isOldInfo = true;
                }
            } catch (Exception e) {
                log.error("时间转换异常：{}", e);
            }
            if (isOldInfo) {
                bankerSite = new YxBankerSite();
                bankerSite.setReleased(1);
            }
        }
        return bankerSite;
    }

    public int deleteSite(Integer id) {
        return bankerSiteMapper.deleteByPrimaryKey(id);
    }

    public void checkSiteInfo() {
        // 供应商新增商品之前，需判断该供应商品牌是否存着/是否上下架
        YxBanker userInfo = bankerService.getUserInfo();
        Example example = new Example(YxBankerSite.class);
        example.createCriteria().andEqualTo("bankerId", userInfo.getId());
        YxBankerSite bankerSite = bankerSiteMapper.selectOneByExample(example);

        if (bankerSite == null) {
            throw new ApiException("您的官网品牌信息不存在，无法新增商品！");
        }
        if (bankerSite != null && bankerSite.getStatus() == 0) {
            throw new ApiException("您的官网品牌信息审核状态暂未通过，无法新增商品！");
        }
    }

    public CommonPage<BankerSiteResponse> selectList(BankerSiteRequest bankerSiteRequest) {
        PageHelper.startPage(bankerSiteRequest.getPageNum(), bankerSiteRequest.getPageSize());
        List<BankerSiteResponse> pageList = bankerSiteMapper.selectList(bankerSiteRequest);
        if(!CollectionUtils.isEmpty(pageList)) {
            for(BankerSiteResponse bsr : pageList) {
                if (null == bsr.getBrandType()) {
                    bsr.setBrandType(bsr.getBankerType());
                }
                if(bsr.getBankerId() != null) {
                    List<BankerResponse> specialBrand = bankerSiteMapper.getSpecialBrand(bsr.getBankerId());
                    bsr.setBankerResponseList(specialBrand);
                }
            }
        }
        return CommonPage.restPage(pageList);
    }

}
